<template>
  <CompOperate
      :field="field"
      :designer="designer"
      :design-state="designState"
      :parent-list="parentList"
      :parent-widget="parentWidget"
      :sub-form-row-id="subFormRowId"
      :sub-form-row-index="subFormRowIndex"
      :sub-form-col-index="subFormColIndex"
      :index-of-parent-list="indexOfParentList"
      :display-style="field.options.displayStyle"
  >
    <div class="scene-share-call-widget flex-box">
      <div class="item queue flex-box-left">
        <div class="header-area" :style="getStyle('head')">
          <div class="header-item">{{ optionsInfo.deptTitle }}</div>
          <div class="header-item">{{ optionsInfo.visitTitle }}</div>
        </div>
        <div class="content-area" :style="getStyle('content')">
          <div class="content-item" v-for="(item,key) in waitingPatientInfos" :key="`${item.workerId}-${key}`">
            <div class="content-item doctor">
              <ScrollX>
                {{ item.treatmentRoomName || item.treatmentRoomShortName || '\u00a0' }}
              </ScrollX>
            </div>
            <div class="content-item patient" v-if="!!(item.treatingPatient)">
              <span>
                <ScrollX>{{ getCurrentPatient(item) }}</ScrollX>
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="item wait-patient flex-box-right" v-if="true">
        <div class="header-area" :style="getStyle('head')">
          <div class="header-item">{{ optionsInfo.waitTitle }}</div>
        </div>
        <div class="content-area" :style="getStyle('content')">
          <template v-if="optionsInfo?.openScroll && waitingPatientLen > 15">
            <vue-seamless-scroll
                class="scroll"
                :ref="`scroll`"
                :key="widgetKey"
                :classOption="scrollOption"
                :data="waitingPatientFlattenDeep"
            >
              <template v-for="(itemInfo,key) in waitingPatientSummaryInfos">
                <div class="content-wait-patient">
                  <template v-for="(chunk,index) in itemInfo">
                    <div class="chunk-item" :data-index="key*3+index+1">
                      <template v-if="optionsInfo?.patientNumber!=='1'">
                        <template v-if="optionsInfo?.patientNumber==='3'">
                          {{(key * 3 + index + 1).toString().padStart(2, '0')}}
                        </template>
                        <template v-else>
                          {{ chunk?.orderNo || '\u00a0' }}
                        </template>
                      </template>
                      <template v-if="true">
                        {{ chunk?.patientName || '\u00a0' }}
                      </template>
                    </div>
                  </template>
                </div>
              </template>
            </vue-seamless-scroll>
          </template>

          <template v-else v-for="(itemInfo,key) in waitingPatientSummaryInfos">
            <div class="content-wait-patient">
              <template v-for="(chunk,index) in itemInfo">
                <div class="chunk-item" :data-index="key*3+index+1">
                  <template v-if="optionsInfo?.patientNumber!=='1'">
                    <template v-if="optionsInfo?.patientNumber==='3'">
                      {{(key * 3 + index + 1).toString().padStart(2, '0')}}
                    </template>
                    <template v-else>
                      {{ chunk?.orderNo || '\u00a0' }}
                    </template>
                  </template>
                  <template v-if="true">
                    {{ chunk?.patientName || '\u00a0' }}
                  </template>
                </div>
              </template>
            </div>
          </template>
        </div>
      </div>
    </div>
  </CompOperate>
</template>

<script>
import {v4 as uuid} from 'uuid'
import {pxToVw} from '@/utils/common';
import emitter from "@/utils/designer/emitter";
import ScrollX from '@c/public/seamlessScroll/ScrollX.vue'
import CompOperate from "@c/public/form-designer/devType/modules/compOperate.vue";
import mixin from "@sc/templateDetails/modules/homeMiddle/fieldMixin";
import {buildParentApi} from "@/utils/designer/util";
import vueSeamlessScroll from 'vue-seamless-scroll'
import Template from "@sc/template/index.vue";

let buildParent = buildParentApi();
export default {
  name: "scene-waiting-share-call-widget",

  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件

  mixins: [emitter, mixin],

  components: {
    Template,
    CompOperate,
    ScrollX,
    vueSeamlessScroll
  },

  props: {
    widget: Object,
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
    designState: {
      type: Boolean,
      default: false,
    },
    devType: {
      type: Boolean,
      default: false,
    },
    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },

    headTitle: {
      type: String,
      default: "",
    },
    visibleTitle: {
      type: Boolean,
    },
  },

  data() {
    return {
      week: '',
      widgetKey: uuid(),
      mockOpen: false,
      optionsInfo: Object(),
    }
  },

  computed: {

    waitingPatientLen() {
      const lens = this.waitingPatientSummaryInfos.map(item => item.length)
      return lens.reduce((sum, num) => (sum + num), 0)
    },

    scrollOption() {
      const {waitingNumber = 15, waitingVisitStep = 1, openScroll = true} = (this.optionsInfo);
      let waitPatientListFlattenDeep = (this.waitingPatientFlattenDeep);
      return {
        hoverStop: true,
        direction: 1,                               // 0向下 1向上 2向左 3向右
        isSingleRemUnit: true,
        step: [1, 1.5, 2, 2.5, 3][waitingVisitStep - 1], // 数值越大速度滚动越快
        limitMoveNum: openScroll && (waitPatientListFlattenDeep.length > 15) ? waitingNumber : 999999, // 开始无缝滚动的数据量 this.dataList.length
      }
    },

    // 设置的行内样式
    getStyle() {
      return function (val) {
        const self = this;
        let info = (self.optionsInfo) || Array();
        let Obj = Object();
        switch (val) {
          case 'content':
            Reflect.set(Obj, 'height', pxToVw(info.contentHeight));
            return Obj;
          case 'head':
            Reflect.set(Obj, 'height', pxToVw(info.headHeight));
            Reflect.set(Obj, 'color', `${(info.headerFontColor)}`);
            Reflect.set(Obj, 'background', `${(info.headerBackgroundColor)}`);
            return Obj;
        }
      }
    },

    // 候诊队列数据
    waitingPatientInfos() {
      let devType = (this.devType);
      let {showRowNums} = (this.optionsInfo);
      let WaitingPatientList = this.$store.getters['getWaitingPatientInfo'];
      if (devType) {
        if (WaitingPatientList.apiData.length > showRowNums) {
          return WaitingPatientList.apiData.slice(0, showRowNums);
        } else {
          let arr = (new Array(showRowNums - WaitingPatientList.apiData.length).fill({}));
          return [...WaitingPatientList.apiData, ...arr];
        }
      } else {
        if (WaitingPatientList.mockData.length > showRowNums) {
          return WaitingPatientList.mockData.slice(0, showRowNums);
        } else {
          let arr = (new Array(showRowNums - WaitingPatientList.mockData.length).fill({}));
          return [...WaitingPatientList.mockData, ...arr];
        }
      }
    },

    // 等候就诊患者
    waitingPatientFlattenDeep() {
      let waitPatientInfo = this.waitingPatientSummaryInfos;
      return this.$lodash.flattenDeep(waitPatientInfo)
    },

    //等待就诊的患者
    waitingPatientSummaryInfos() {
      let devType = (this.devType);
      let {showRowNums} = (this.optionsInfo);
      let WaitingPatientList = this.$store.getters['getWaitingPatientInfo'];
      let tempList = Array();
      if (devType) {
        tempList = (WaitingPatientList.apiData);
      } else {
        tempList = (WaitingPatientList.mockData);
      }
      //去重
      let list = Array();
      const setArr = new Set()
      list = tempList.filter(item => {
        if (!setArr.has(item.workerId)) {
          setArr.add(item.workerId)
          return true
        }
        return false
      })
      let summaryList = Array();
      if (list.length > showRowNums) {
        summaryList = list.slice(0, showRowNums);
      } else {
        let arr = (new Array(5 - list.length).fill({}));
        summaryList = [...list, ...arr];
      }
      let summary = this.$lodash.map(summaryList, "waitPatientList");
      let flattenArr = this.$lodash.flattenDeep(summary);
      let uniqByArr = this.$lodash.uniqBy(flattenArr, 'queuingId');
      if (uniqByArr.length > 15) {
        const arr = uniqByArr.filter(item => item)
        const len = arr.length
        if (len % 3 === 0) {
          return this.$lodash.chunk(arr, 3)
        }
        const targetLength = Math.ceil(len / 3) * 3
        const flattenArr2 = [...arr]
        for (let i = len; i < targetLength; i++) {
          flattenArr2.push({}); // 使用默认值填充剩余空间  
        }
        return this.$lodash.chunk(flattenArr2, 3)
      } else {
        let arr = (new Array(15 - uniqByArr.length).fill({}));
        let flattenArr2 = [...uniqByArr, ...arr];
        return this.$lodash.chunk(flattenArr2, 3)
      }
    },

    // 当前就诊的患者|| 医生暂停接诊
    getCurrentPatient() {
      return function (val) {
        /**
         * 在线状态 0在线 1暂停 2退出
         */
        let type = parseInt(val.onlineStatus);
        switch (type) {
          case 0:
          case 2:
            if (!!(val.treatingPatient) && !!(val.treatingPatient.length)) {
              let currentPatient = Array();
              (val.treatingPatient).forEach((item) => {
                let temp = `${(item.orderNo) || '\u00a0'} ${(item.patientName) || '\u00a0'}`
                currentPatient.push(temp)
              })
              return (this.$lodash.join(currentPatient, '  '));
            } else {
              return '\u00a0'
            }
          case 1:
            return '暂停接诊';
        }
      }
    },
  },

  created() {
    this.registerToRefList();
    this.initEventHandler();
    this.handleOnCreated();
  },

  mounted() {
    this.handleOnMounted();
  },

  methods: {
    // 接收父组件传递过来的数据
    executeMethod(key, data) {
      switch (key) {
        case "patientListInfo":
          let patientList = this.$lodash.cloneDeep(data);
          buildParent.executeParentMethod('writeLog', JSON.stringify({sign: '模板-患者信息', key: key, data: data}));
          this.$store.dispatch('setWaitingPatientInfo', patientList)
          break
      }
    }
  },

  watch: {
    field: {
      handler: function (val) {
        this.widgetKey = uuid();
        let key = (val.options.config);
        this.optionsInfo = (val.options[key]);
      },
      deep: true,
      immediate: true
    }
  },

  destroyed() {
    this.unregisterFromRefList();
  },
};
</script>

<style lang="scss" scoped>
.scene-share-call-widget {
  padding: 28px 30px 10px 30px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  color: #333;
  height: auto;
  font-size: 50px;
  overflow: hidden;

  .item {
    border-radius: 20px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    border: none;

    .header-area {
      width: 100%;
      height: 120px;
      background: rgba(0, 89, 179, 1);
      display: flex;

      .header-item {
        flex: 1;
        height: 100%;
        flex-direction: unset;
        font-size: 50px;
        display: flex;
        justify-content: center; /* 水平居中 */
        align-items: center; /* 垂直居中 */
      }
    }

    .content-area {
      display: flex;
      flex-direction: column;

      .scroll {
        overflow: hidden;
      }

      .content-item {
        background: white;
        margin-top: 8px;
        font-size: 50px;
        width: 100%;
        color: #333333;
        display: flex;
        padding: 4.5px 0;
        justify-content: center; /* 水平居中 */
        align-items: center; /* 垂直居中 */
        flex: 1;
        overflow: hidden;

        &:first-child {
          margin-top: 0;
        }

        span {
          border-radius: 12px;
          padding: 12px 20px;
          font-size: 48px;
          line-height: 52px;
          margin-top: -8px;
          display: inline-block;
          background: rgba(0, 89, 179, 0.2);
          @include singleEllipsis(calc(84%))
        }
      }
    }
  }

  .queue {
    flex-basis: 40%;
    margin-right: 20px;
    background: transparent;
  }

  .wait-patient {
    flex-basis: calc(100% - 40% - 20px);

    .content-area {
      display: flex;
      // flex-wrap: wrap;
      margin-top: 0;
      // flex-direction: row;
    }

    .content-wait-patient {
      text-align: center;
      display: flex;
      width: 100%;
      flex: 1;
      flex-shrink: 0;
      height: auto;
      flex-direction: row;

      .chunk-item {
        flex: 1;
        padding: 30px 20px;
        flex-basis: calc(100% / 3);
        overflow: hidden;
        white-space: nowrap;
        @include singleEllipsis(calc(100% / 3));

        &:nth-child(2n) {
          border-left: 2px rgba(0, 0, 0, 0.2) solid;
          border-right: 2px rgba(0, 0, 0, 0.2) solid;
        }
      }

      &:nth-child(2n) {
        background: rgba(248, 248, 248, 1);
      }
    }

  }
}
</style>
